/*
 * Copyright (C) 2010 Graham Allan
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package edu.strath.cis.grallan.findbugs.adaptiveranking.gui;

import java.awt.Component;

import javax.swing.ProgressMonitor;

import edu.strath.cis.grallan.findbugs.adaptiveranking.RankingProgressCallback;
import edu.umd.cs.findbugs.gui2.IViewController;

/**
 * Decorates a RankingProgressCallback object with a {@link ProgressMonitor} to display feedback to
 * the user. Calls back to the given {@link RankingProgressCallback} at each noteworthy stage.
 * 
 * @author Graham Allan (grallan@cis.strath.ac.uk)
 */
public class RankingModeProgressMonitor implements RankingProgressCallback {
	private ProgressMonitor progressMonitor;
	private int progress = 0;
	private int maximum = 0;
	boolean alreadyCancelled = false;

	private IViewController viewController;
	private final RankingProgressCallback rankingMode;
	private final Component parent;
	private final String message;

	public RankingModeProgressMonitor(Component parent, IViewController viewController,
			RankingProgressCallback rankingMode, String message) {
		this.parent = parent;
		this.viewController = viewController;
		this.rankingMode = rankingMode;
		this.message = message;
	}

	public void notifyRankingComputed() {
		if (!alreadyCancelled) {
			rankingMode.notifyRankingComputed();
		}

		viewController.showView();
		progressMonitor.setProgress(maximum);
	}

	public void notifySingleRankComputed() {
		progress++;
		progressMonitor.setProgress(progress);
		progressMonitor.setNote(progress + " / " + maximum);

		if (progressMonitor.isCanceled() && !alreadyCancelled) {
			viewController.showView();
			alreadyCancelled = true;
		}

		rankingMode.notifySingleRankComputed();
	}

	public void notifyRankingStarted(int numTotalBugs) {
		viewController.hideView();
		maximum = numTotalBugs;
		progressMonitor = new ProgressMonitor(parent, message, "0 / " + maximum, 0, maximum);
		progressMonitor.setMillisToDecideToPopup(1);
		progressMonitor.setMillisToPopup(10);
		progress = 0;
		alreadyCancelled = false;

		rankingMode.notifyRankingStarted(numTotalBugs);
	}

	public void notifyRefreshComplete() {
		rankingMode.notifyRefreshComplete();
	}
}